﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NetCore8Demo.Tool
{
    public class FileTool
    {

        public static void DeleteOldImages(string path, TimeSpan olderThan)
        {
            try
            {
                if (!Directory.Exists(path))
                {
                    return;
                }

                DateTime now = DateTime.Now;
                string[] files = Directory.GetFiles(path);

                foreach (string file in files)
                {
                    FileInfo fileInfo = new FileInfo(file);
                    if ((now - fileInfo.LastWriteTime) > olderThan && IsImageFile(fileInfo.Extension))
                    {
                        File.Delete(file);
                    }
                }

                DeleteEmptyFolders(path);
            }
            catch (Exception ex)
            {
                Log.WriteLog("系统报错", "删除图片报错 "+ "\r\n"+ ex.Message);
            }
        }

        public static bool IsImageFile(string extension)
        {
            string[] imageExtensions = { ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff" };
            return Array.Exists(imageExtensions, ext => ext.Equals(extension, StringComparison.OrdinalIgnoreCase));
        }

        static void DeleteEmptyFolders(string path)
        {
            try
            {
                if (!Directory.Exists(path))
                {
                    Console.WriteLine("指定的目录不存在。");
                    return;
                }

                // 获取当前目录下的所有子目录
                string[] subDirectories = Directory.GetDirectories(path);

                foreach (string directory in subDirectories)
                {
                    // 递归删除子目录中的空文件夹
                    DeleteEmptyFolders(directory);
                }

                // 检查当前目录是否为空
                if (Directory.GetFiles(path).Length == 0 && Directory.GetDirectories(path).Length == 0)
                {
                    Directory.Delete(path);
                    Console.WriteLine($"已删除空文件夹: {path}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"发生错误: {ex.Message}");
            }
        }


    }
}
